package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.base.domain.Config;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;




    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }

    @Override
    public BpmnInfo get(Long id) {

        return bpmnInfoMapper.selectByPrimaryKey(id);
    }


    @Override
    public void save(BpmnInfo bpmnInfo) {

        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public void update(BpmnInfo bpmnInfo) {


    }


    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            bpmnInfoMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }

    @Override
    public void deploy(String bpmnInfoPath, String bpmnType, String info) throws FileNotFoundException {

        Deployment deploy = repositoryService.createDeployment()
                .addInputStream(bpmnInfoPath, new FileInputStream(new File(SystemConfig.getProfile(), bpmnInfoPath)))
                .deploy();

        // 给bpmnInfo 设置值
        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setBpmnPath(bpmnInfoPath); //bpmn 文件路径
        bpmnInfo.setBpmnType(bpmnType);     // 文件类型
        bpmnInfo.setInfo(info);             // 备注
        bpmnInfo.setDeployTime(new Date()); // 部署时间
        bpmnInfo.setDeploymentId(deploy.getId());   // 设置部署 ID

        //创建流程定义查询
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploy.getId())
                // 约定 一个流程图只能部署一次
                .singleResult();

        //设置activity流程定义生成的主键
        bpmnInfo.setActProcessId(processDefinition.getId());
        //设置activity流程定义生成的key
        bpmnInfo.setActProcessKey(processDefinition.getKey());
        //设置流程(图)名称
        bpmnInfo.setBpmnName(processDefinition.getName());

        // 插入流程定义
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public void delete(Long id) {
        // 流程定义对象 bpmnInfo
        BpmnInfo bpmnInfo = get(id);
        bpmnInfoMapper.deleteByPrimaryKey(id);
        File file = new File(SystemConfig.getProfile(), bpmnInfo.getBpmnPath());
        //判断文件是否存在
        if(file.exists()){
            file.delete();
        }

        // 如果流程图对应的流程实例启动了，也需要删除

        // 把相关流程表一起删掉 级联删除
        // 删除部署 通过获取获取部署 ID 一起删除掉
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId(),true);
    }

    @Override
    public InputStream readResource(String deploymentId, String type) {
        // 通过流程定义对象获取
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery()
                //部署 ID
                .deploymentId(deploymentId)
                // 获取最新版本
                .latestVersion()
                .singleResult();

        InputStream inputStream = null;

        if("xml".equalsIgnoreCase(type)){
            // 获取资源名字
            String resourceName = definition.getResourceName();
            //获取资源作为流 通过
            inputStream = repositoryService.getResourceAsStream(deploymentId, resourceName);
        } else if("png".equalsIgnoreCase(type)){
            // 图片  Bpmn 模型 通过定义id获取
            BpmnModel model = repositoryService.getBpmnModel(definition.getId());
            // 获取默认流程图生成器
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            //generateDiagram(流程模型,需要高亮的节点,需要高亮的线条,后面三个参数都表示是字体)
            inputStream = generator.generateDiagram(model, Collections.EMPTY_LIST, Collections.EMPTY_LIST,
                    "宋体","宋体","宋体");
            return inputStream;
        }
        return inputStream;
    }

    @Override
    public BpmnInfo queryByType(String type) {
        return bpmnInfoMapper.selectByType(type);


    }


}
